//
//  NvLiveWindowPanelView.m
//  SDKDemo
//
//  Created by meishe01 on 2018/5/30.
//  Copyright © 2018年 meishe. All rights reserved.
//

#import "NvLiveWindowPanelView.h"
#import "NVHeader.h"
#import "NvsLiveWindow.h"
#import "NvWeakTimer.h"
#import "NvSDKUtils.h"

@interface NvLiveWindowPanelView () <NvsStreamingContextDelegate> {
    NvsTimeline *_timeline;
    UIButton *_playbackBtn;
    UILabel *_currentTimeLabel;
    UIButton *_volumnBtn;
    UILabel *_durationLabel;
    NvWeakTimer *_timer;
    UITapGestureRecognizer *_tap,*_tapScreen;
    int64_t every;
}

@property (nonatomic, assign) int64_t duration;

@end

@implementation NvLiveWindowPanelView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubviews:frame];
    }
    return self;
}

- (void)addSubviews:(CGRect)rect {
    _liveWindow = [[NvsLiveWindow alloc] initWithFrame:rect];
    [self addSubview:_liveWindow];
    _controlPanelView = [UIView new];
    _controlPanelView.backgroundColor = [UIColor nv_colorWithHexARGB:@"#80000000"];
    [self addSubview:_controlPanelView];
    [_controlPanelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.bottom.equalTo(self->_liveWindow);
        make.height.equalTo(@(40 * SCREANSCALE));
    }];
    _playbackBtn = [UIButton new];
    [_playbackBtn setImage:[NvUtils imageWithName:@"NvPlayback"] forState:UIControlStateNormal];
    [_controlPanelView addSubview:_playbackBtn];
    [_playbackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(@0);
        make.width.equalTo(self->_controlPanelView.mas_height);
    }];
    _currentTimeLabel = [UILabel new];
    _currentTimeLabel.text = @"00:00";
    _currentTimeLabel.textColor = [UIColor whiteColor];
    _currentTimeLabel.font = [NvUtils fontWithSize:10];
    CGSize size = [_currentTimeLabel sizeThatFits:CGSizeMake(MAXFLOAT, MAXFLOAT)];
    [_controlPanelView addSubview:_currentTimeLabel];
    [_currentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_playbackBtn.mas_right);
        make.centerY.equalTo(self->_controlPanelView);
        make.width.equalTo(@(size.width));
    }];
    _volumnBtn = [UIButton new];
    [_volumnBtn setImage:[NvUtils imageWithName:@"NvVolumn"] forState:UIControlStateNormal];
    [_controlPanelView addSubview:_volumnBtn];
    [_volumnBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(@0);
        make.width.equalTo(self->_controlPanelView.mas_height);
    }];
    _durationLabel = [UILabel new];
    _durationLabel.text = @"00:00";
    _durationLabel.textColor = [UIColor whiteColor];
    _durationLabel.font = [NvUtils fontWithSize:10];
    [_controlPanelView addSubview:_durationLabel];
    [_durationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self->_volumnBtn.mas_left);
        make.centerY.equalTo(self->_controlPanelView);
        make.width.equalTo(@(size.width));
    }];
    _progressSlider = [UISlider new];
    [_progressSlider setThumbImage:[NvUtils imageWithName:@"NvSliderHandle"] forState:UIControlStateNormal];
    [_progressSlider setMinimumTrackTintColor:[UIColor nv_colorWithHexARGB:@"#FF4A90E2"]];
    [_progressSlider setMaximumTrackTintColor:[UIColor nv_colorWithHexARGB:@"#FF979797"]];
    [_controlPanelView addSubview:_progressSlider];
    [_progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_currentTimeLabel.mas_right).offset(7 * SCREANSCALE);
        make.right.equalTo(self->_durationLabel.mas_left).offset(-7 * SCREANSCALE);
        make.centerY.equalTo(self->_controlPanelView);
    }];
    
    [_playbackBtn addTarget:self action:@selector(playbackBtnClicked) forControlEvents:(UIControlEventTouchUpInside)];
    [_volumnBtn addTarget:self action:@selector(volumnBtnClicked) forControlEvents:(UIControlEventTouchUpInside)];
    [_progressSlider addTarget:self action:@selector(progressSliderValueChanged) forControlEvents:(UIControlEventValueChanged)];
    
    [_progressSlider addTarget:self action:@selector(sliderValueEnd:) forControlEvents:UIControlEventTouchUpInside];
    
    _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    [_liveWindow addGestureRecognizer:_tap];
}

- (void)setHiddenPanelTimer {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NvWeakTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideControlPanel:) userInfo:nil repeats:NO dispatchQueue:dispatch_get_main_queue()];
}

- (void)addTapScreenPause {
    if (_tapScreen) {
        return;
    }
    _tapScreen = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapScreen:)];
    [_liveWindow addGestureRecognizer:_tapScreen];
}

- (void)hiddenVolumeButton {
    _volumnBtn.hidden = YES;
    [_durationLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(-13*SCREANSCALE));
        make.centerY.equalTo(self->_controlPanelView);
        make.width.equalTo(@(35*SCREANSCALE));
    }];
}

- (void)singleTapScreen:(UITapGestureRecognizer *)recognizer {
    if (_controlPanelView.hidden) {
        if (_forceHiddenControlPanel) {//如果强制隐藏则直接播放
            if ([NvSDKUtils getSDKContext].getStreamingEngineState != NvsStreamingEngineState_Playback) {
                if (![[NvSDKUtils getSDKContext] playbackTimeline:_timeline startTime:self.currentTime endTime:_timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
                    NSLog(@"播放时间线失败！");
                    return;
                }
                if ([self.delegate respondsToSelector:@selector(playback)]) {
                    [self.delegate playback];
                }
            } else {
                [[NvSDKUtils getSDKContext] stop];
            }
        } else {//如果不是强制隐藏则显示并添加定时器
            [self showControllPanel];
        }
    } else {
        if ([NvSDKUtils getSDKContext].getStreamingEngineState != NvsStreamingEngineState_Playback) {
            if (![[NvSDKUtils getSDKContext] playbackTimeline:_timeline startTime:self.currentTime endTime:_timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
                NSLog(@"播放时间线失败！");
                return;
            }
            if ([self.delegate respondsToSelector:@selector(playback)]) {
                [self.delegate playback];
            }
        } else {
            [[NvSDKUtils getSDKContext] stop];
        }
        [self setHiddenPanelTimer];
    }
}

- (void)removeTapScreenPause {
    if (_tapScreen) {
        [_liveWindow removeGestureRecognizer:_tapScreen];
        _tapScreen = nil;
    }
}

- (void)singleTap:(UITapGestureRecognizer *)recognizer {
    if (_controlPanelView.hidden == YES) {
        _controlPanelView.hidden = NO;
        [self setHiddenPanelTimer];
    } else {
        [self playbackBtnClicked];
    }
}

- (void)showControllPanel {
    if (_forceHiddenControlPanel) {
        return;
    }
    _controlPanelView.hidden = NO;
    [self setHiddenPanelTimer];
}

- (void)setEditMode:(NvEditMode)editMode {
    _editMode = editMode;
    float liveWindowWidth = self.bounds.size.width;
    float liveWindowHeight = self.bounds.size.height;
    if (_editMode == NvEditMode16v9) {
        liveWindowHeight = liveWindowWidth * 9 / 16;
    } else if (_editMode == NvEditMode1v1) {
        liveWindowHeight = liveWindowWidth;
    } else if (_editMode == NvEditMode9v16) {
        liveWindowWidth = liveWindowHeight * 9 / 16;
    } else if (_editMode == NvEditMode4v3) {
        liveWindowHeight = liveWindowWidth * 3 / 4;
    } else if (_editMode == NvEditMode3v4) {
        liveWindowWidth = liveWindowHeight * 3 / 4;
    }
    _liveWindow.width = liveWindowWidth;
    _liveWindow.height = liveWindowHeight;
    _liveWindow.centerX = self.centerX;
    _liveWindow.centerY = self.centerY;
}

- (void)setCurrentTime:(int64_t)currentTime {
    _currentTime = currentTime;
    _currentTimeLabel.text = [NvUtils convertTimecode:_currentTime];
}

- (void)setDuration:(int64_t)duration {
    _duration = duration;
    _durationLabel.text = [NvUtils convertTimecode:duration];
}

- (void)connectTimeline:(NvsTimeline *)timeline {
    if (![[NvSDKUtils getSDKContext] connectTimeline:timeline withLiveWindow:_liveWindow]) {
        NSLog(@"连接预览窗口失败！");
        return;
    }
    _timeline = timeline;
    [NvSDKUtils getSDKContext].delegate = self;
    self.duration = timeline.duration;
}

- (void)seekTimeline:(int64_t)pos {
    if (![[NvSDKUtils getSDKContext] seekTimeline:_timeline timestamp:pos videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:NvsStreamingEngineSeekFlag_ShowCaptionPoster | NvsStreamingEngineSeekFlag_ShowAnimatedStickerPoster])
        NSLog(@"Failed to seek timeline!");
}

- (void)playAtTime:(int64_t)pos {
    if (!_timeline)
        return;
    if ([self isPlayback]) {
        [[NvSDKUtils getSDKContext] stop];
    } else {
        if (![[NvSDKUtils getSDKContext] playbackTimeline:_timeline startTime:pos endTime:_timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
            NSLog(@"播放时间线失败！");
            return;
        }
        if ([self.delegate respondsToSelector:@selector(playback)]) {
            [self.delegate playback];
        }
    }
    [self setHiddenPanelTimer];
}

- (void)playBackStart:(int64_t)start end:(int64_t)end {
    if (![[NvSDKUtils getSDKContext] playbackTimeline:_timeline startTime:start endTime:end videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
        NSLog(@"播放时间线失败！");
        return;
    }
    [self setHiddenPanelTimer];
}

- (void)playbackBtnClicked {
    if (!_timeline)
        return;
    if ([self isPlayback]) {
        [[NvSDKUtils getSDKContext] stop];
    } else {
        if (![[NvSDKUtils getSDKContext] playbackTimeline:_timeline startTime:self.currentTime endTime:_timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
            NSLog(@"播放时间线失败！");
            return;
        }
        if ([self.delegate respondsToSelector:@selector(playback)]) {
            [self.delegate playback];
        }
    }
    [self setHiddenPanelTimer];
}

- (void)hideControlPanel:(NSTimer *)timer {
    if (!_controlPanelView.hidden)
        _controlPanelView.hidden = YES;
}

- (void)volumnBtnClicked {
    if ([self.delegate respondsToSelector:@selector(volumnClicked)]) {
        [self.delegate volumnClicked];
    }
}

- (void)sliderValueEnd:(UISlider*)slider {
    _timer = [NvWeakTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideControlPanel:) userInfo:nil repeats:NO dispatchQueue:dispatch_get_main_queue()];
}

- (void)progressSliderValueChanged {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _controlPanelView.hidden = NO;
    
    self.currentTime = lround(_progressSlider.value * _duration);
    [self seekTimeline:self.currentTime];
    if ([self.delegate respondsToSelector:@selector(sliderValueChanged:)]) {
        [self.delegate sliderValueChanged:self.progressSlider.value];
    }
}

- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position {
    self.currentTime = position;
    [self.progressSlider setValue:(float)position / _duration animated:YES];
    if ([self.delegate respondsToSelector:@selector(didPlaybackTimelinePosition:position:)]) {
        [self.delegate didPlaybackTimelinePosition:timeline position:position];
    }
}

- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    [self setHiddenPanelTimer];
    if (_controlPanelView.hidden && !self.forceHiddenControlPanel) {
        _controlPanelView.hidden = NO;
    }
    if ([self.delegate respondsToSelector:@selector(didPlaybackStopped:)]) {
        [self.delegate didPlaybackStopped:timeline];
    }
}

- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    [self.progressSlider setValue:1 animated:YES];
    [self setHiddenPanelTimer];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.currentTime = 0;
        self->_currentTimeLabel.text = [NvUtils convertTimecode:0];
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf)self = weakSelf;
            [self seekTimeline:0];
            [self.progressSlider setValue:0 animated:YES];
        });
        if ([self.delegate respondsToSelector:@selector(didPlaybackEOF:)]) {
            [self.delegate didPlaybackEOF:timeline];
        }
    });
}

- (BOOL)isPlayback {
    return [[NvSDKUtils getSDKContext] getStreamingEngineState] == NvsStreamingEngineState_Playback;
}

- (void)dealloc {
    // 不要在dealloc 中停止引擎，因为dealloc的调用受系统控制，如果在这里停止引擎，可能引发需要播放的画面在莫名其妙的时机被停止播放。
//    [[NvSDKUtils getSDKContext] stop];
}

- (void)setForceHiddenControlPanel:(BOOL)forceHiddenControlPanel {
    _forceHiddenControlPanel = forceHiddenControlPanel;
    if (forceHiddenControlPanel) {
        _controlPanelView.hidden = YES;
        [_liveWindow removeGestureRecognizer:_tap];
    }
}

- (void)didStreamingEngineStateChanged:(NvsStreamingEngineState)state {
    if (state == NvsStreamingEngineState_Playback) {
        [_playbackBtn setImage:[NvUtils imageWithName:@"NvPause"] forState:UIControlStateNormal];
    } else {
        [_playbackBtn setImage:[NvUtils imageWithName:@"NvPlayback"] forState:UIControlStateNormal];
    }
    if ([self.delegate respondsToSelector:@selector(didStreamingEngineStateChanged:)]) {
        [self.delegate didStreamingEngineStateChanged:state];
    }
}
@end
